package edu.dev.tfile.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.dev.tfile.common.Utils;

public class UploadService extends HttpServlet {

	private static final long serialVersionUID = 3118155024795514595L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String baseDir = Utils.getConfig("upload_path");
		baseDir = baseDir.replace("\\", "/");
		if ("/".equals(baseDir.substring(baseDir.length() - 1))) {
			baseDir = baseDir.substring(0, baseDir.length() - 1);
		}
		String fileName = req.getHeader("X_FILENAME");
		String uploadFolder = URLDecoder.decode(req.getHeader("X_FOLDER_PATH"), "UTF-8");
		fileName = URLDecoder.decode(fileName, "UTF-8");
		String fileRealFolder = "".equals(uploadFolder) ? "baseDir" : baseDir + "/" + uploadFolder;
		File fileDir = new File(fileRealFolder);
		if (!fileDir.exists()) {
			fileDir.mkdirs();
		}
		File file = new File(fileRealFolder + "/" + fileName);
		if (file.exists()) {
			file.delete();
		}
		file.createNewFile();
		OutputStream os = new FileOutputStream(file);
		InputStream is = req.getInputStream();
		int byteread = 0;
		byte[] b = new byte[1024];
		while ((byteread = is.read(b)) != -1) {
			os.write(b, 0, byteread);
		}
		os.flush();
		is.close();
		os.close();
	}

}
